var express = require('express');
var router = express.Router();
var User=require('../models/user.server.model.js');
var request=require('request');
var cheerio=require('cheerio');
/* GET home page. */
router.get('/', function(req, res, next) {
    request('http://www.hfjy.com/',function(error,response,body){
        //$=cheerio.load(body);
        if(!error&&response.statusCode==200){
            $=cheerio.load(body);
            var tt=$('.nav_menu').html();
            res.send(tt);
        }else{
            res.send("hh")
        }

    })
    //res.render('index', { title: 'JSON博客' });
});
router.get('/index.html', function(req, res, next) {
    console.log("eee")
    res.render('index', { title: 'JSON博客' });
});
router.get('/login.html', function(req, res, next) {
    res.render('login', { title: '登录1',msg:'' });
});
router.post('/dologin.html', function(req, res, next) {
    var post=req.body;
    User.findOne({username:post.username},function(error,docs){
        if(error){
            res.send(error);
        }
        if(docs!=null && post.password==docs.password){
            req.session.username=post.username;
            return res.redirect('/admin.html');
        }else{
            res.render('login', { title: '登录',msg:'帐号或密码错误' });
             res.end()
        }
    });

});
router.get('/admin.html', function(req, res, next) {

    res.render('admin', { title: '注册',username:req.session.username });
});
router.get('/register.html', function(req, res, next) {

    res.render('register', { title: '注册' });
});
router.post('/doregister.html', function(req, res, next) {
    post=req.body;
    if(!post.username||!post.password)
    res.send('error');
    var user=new User({
        username:post.username,
        password:post.password
    });
    user.save(function(err){
        if(err)res.send('add error');
        res.redirect('/login.html');
    })
    //res.render('register', { title: '注册' });
});
router.get('/post.html', function(req, res, next) {
    res.render('post', { title: '发贴' });
});

module.exports = router;
